# -*- coding: utf-8 -*-

# Copyright (C) 2017 Intel Corporation.  All rights reserved.
# Copyright (c) WanSheng Intelligent Corp. All rights reserved.

#
# Licensed under the Apache License, Version 2.0 (the "License");
#

import json
from coapthon.client.helperclient import HelperClient
from coapthon import defines

from wa_edge_iot.internals.rd_parser import RDParser
from wa_edge_iot.framework.rd_query_param import RDQueryParam

# each RDUtility represent RD operations on a specific server
class RDUtility(object):
    def __init__(self,
                 wagent, 
                 ip,
                 port):
        self.__uri = "coap://" + ip + ":" + str(port)
        self.ip = ip
        self.port = port
        self.__iagent_mgr = wagent

    def query_rd(self, query=None):
        assert query is None or isinstance(query, RDQueryParam)
        uri = "/rd"
        try:
            if query:
                uri = uri +  query.to_query_string()
            print("query_rd, uri:" + uri)
            client = HelperClient(server=(self.ip, self.port))
            response = client.get(uri)
            client.close()
            
            if response is None:
                return None
            
            if response.code == defines.Codes.CONTENT.number:
                devices = RDParser.parse_device(str(response.payload))
                return devices

        except Exception as   e:
            print("query_rd: " + str(e))
            client.close()
        
        
        return None


    def create_monitor(self, monitor_name, parameters = None ):
        
        if parameters is not None and not isinstance(parameters, RDQueryParam):
            print("Inalid parameter type: " + str(type(parameters)))
            return -1
 
        try:
            client = HelperClient(server=(self.ip, self.port))
            
            publish_uri = "coap://127.0.0.1:" + str(self.__iagent_mgr.listen_port()) + "/rdm"
            
            if parameters is None:
                parameters = RDQueryParam()
                
            parameters.query["app-id"] = self.__iagent_mgr.app_id()
            parameters.query["monitor-tag"] = monitor_name
                
            payload = (defines.Content_types["application/json"],
                       parameters.to_monitor_string(publish_uri))
            response = client.post("/rd/monitor", payload)
            
            if response is None:
                return None
            
            if response.code == defines.Codes.CREATED.number or response.code == defines.Codes.CHANGED.number:
                monitor_id = str(response.payload)
                print("monitor_id is", monitor_id)
                client.close()
                return monitor_id
            
        except Exception as e:
            print("create_monitor: " + str(e))
            import traceback
            traceback.print_exc()
        
        client.close()
        return None


    def remove_monitor(self, moniter_id):
        uri = "/rd/monitor" + "?id=" + moniter_id
        try:
            client = HelperClient(server=(self.ip, self.port))
            print(("DELETE : " + self.__uri + uri))
            response = client.delete(uri, None, timeout=1)
            
            if response == None :
                print ("remove_monitor timeout! - Not implemented by agent")
                client.close()
                return True

            if response.code == defines.Codes.DELETED.number:
                client.close()
                return True
        except Exception as e:
            print("remove_monitor: " + str(e))
            
        client.close()
        return False
